const { Controller } = require("egg");

class BaseController extends Controller {
	async index() {
		const { ctx, service } = this;
		const { pageNum, pageSize, ...where } = ctx.query;

		const list = await service[this.table].list(
			isNaN(pageNum) ? 1 : parseInt(pageNum),
			isNaN(pageSize) ? 10 : parseInt(pageSize),
			where
		);
		ctx.body = list;
	}

	async create() {
		const { ctx, service } = this;
		ctx.validate(this.createRule || {}, ctx.request.body);
		const data = ctx.request.body;
		const res = await service[this.table].create(data);
		res ? this.success(200, "创建成功") : this.error(201, "创建失败");
	}

	async update() {
		const { ctx, service } = this;
		ctx.validate(this.updateRule || {}, ctx.request.body);
		const data = ctx.request.body;
		const { id } = ctx.params;
		data.id = id;
		const res = await service[this.table].update(data);
		res ? this.success(200, "更新成功") : this.error(201, "更新失败");
	}

	async destroy() {
		const { ctx, service } = this;
		const { id } = ctx.params;
		const res = await service[this.table].destroy(id);
		res ? this.success(200, "删除成功") : this.error(201, "删除失败");
	}

	success(code, message) {
		this.ctx.body = {
			code,
			message
		};
	}

	error(code, message) {
		this.ctx.body = {
			code,
			message
		};
	}
}

module.exports = BaseController;
